//
//  JSNearbyVC.m
//  NiubilityProject
//
//  Created by Apple on 2017/12/4.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "JSNearbyVC.h"
#import "JSNearbyCell.h"
#import "JSHeaebyNaviView.h"
#import "IFMMenuItem.h"
@interface JSNearbyVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *recommentDataSource;
@property (nonatomic, strong) NSString *mouth;
@property (nonatomic, assign) BOOL isNearby;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, weak) JSHeaebyNaviView *naviView;
@property (nonatomic, strong) NSMutableArray *menuItems;
@property (nonatomic, assign) NSInteger filtrateGender;
@end

@implementation JSNearbyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.filtrateGender = UserGenderMale;
    // Do any additional setup after loading the view.
}
- (void)didInitialized{
    [super didInitialized];
    [self.collectionView registerNib:[UINib nibWithNibName:@"JSNearbyCell" bundle:nil] forCellWithReuseIdentifier:@"JSNearbyCellID"];
    [self.collectionView registerClass:[JSNearbyHeaderTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"JSNearbyHeaderTitleViewID"];
    [self.collectionView registerClass:[JSNearbyHeaderImageView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"JSNearbyHeaderImageViewID"];
}
- (void)setNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated{
    [super setNavigationItemsIsInEditMode:isInEditMode animated:animated];
    JSHeaebyNaviView *naviView = [[JSHeaebyNaviView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.5, 40)];
    self.naviView = naviView;
    self.navigationItem.titleView = naviView;
    JS_WeakSelf(self)
    [RACObserve(self.naviView, isNearby)subscribeNext:^(id x) {
        weakself.isNearby = [x boolValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBManager showLoading];
        });
        [weakself headerRefresh];
    }];
    self.navigationItem.rightBarButtonItem = [QMUINavigationButton barButtonItemWithImage:[UIImage imageNamed:@"home_more_icon"] position:QMUINavigationButtonPositionRight target:self action:@selector(genderSelect:)];
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
        CGFloat w = (SCREEN_WIDTH - kRealValue(10) * 2 - 3) / 4;
        flow.itemSize = CGSizeMake(flat(w), flat(w));
        flow.minimumLineSpacing = 1;
        flow.minimumInteritemSpacing = 1;
        flow.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flow];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
        // 自动改变透明度
        _collectionView.mj_header.automaticallyChangeAlpha = YES;
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        _collectionView.mj_footer.automaticallyChangeAlpha = YES;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (void)setFiltrateGender:(NSInteger)filtrateGender{
    if (_filtrateGender == filtrateGender) {
        return;
    }
    _filtrateGender = filtrateGender;
    [MBManager showLoading];
    [self headerRefresh];
}
- (void)headerRefresh{
    self.page = 1;
    if (self.isNearby) {
        self.mouth = @"nearby";
    }else{
        self.mouth = @"meet";
    }
    [JSNetManager js_courrentProjectRequestWithMouth:self.mouth cache:NO ifShowFinishStatu:NO parameters:@{@"sex":@(self.filtrateGender),@"p":@(self.page),@"token":userManager.curUserInfo.token}.mutableCopy successBlock:^(id response) {
        JSLog(@"%@", response);
        if ([response[@"status"] integerValue] == 90001) {
            JSAlertWithMessge(@"error token");
            return ;
        }
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        [self.dataSource removeAllObjects];
        if (ValidArray(response[@"data"][@"list"])) {
            [self.dataSource addObjectsFromArray:[UserInfo mj_objectArrayWithKeyValuesArray:response[@"data"][@"list"]]];
        }
        [self.collectionView reloadData];
    } failureBlock:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}
- (void)footerRefresh{
    self.page ++;
    if (self.isNearby) {
        self.mouth = @"nearby";
    }else{
        self.mouth = @"meet";
    }
    [JSNetManager js_courrentProjectRequestWithMouth:self.mouth cache:NO ifShowFinishStatu:NO parameters:@{@"sex":@(self.filtrateGender),@"p":@(self.page),@"token":userManager.curUserInfo.token}.mutableCopy successBlock:^(id response) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (ValidArray(response[@"data"][@"list"])) {
            [self.dataSource addObjectsFromArray:[UserInfo mj_objectArrayWithKeyValuesArray:response[@"data"][@"list"]]];
        }
        
        [self.collectionView reloadData];
    } failureBlock:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        self.page --;
    }];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return self.recommentDataSource.count;
    }
    return self.dataSource.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    JSNearbyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JSNearbyCellID" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        if (indexPath.row < self.recommentDataSource.count) {
            cell.user = self.recommentDataSource[indexPath.row];
        }
    }else{
        if (indexPath.row < self.dataSource.count) {
            cell.user = self.dataSource[indexPath.row];
        }
    }
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section) {
            JSNearbyHeaderTitleView *titleV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"JSNearbyHeaderTitleViewID" forIndexPath:indexPath];
            return titleV;
        }
        JSNearbyHeaderImageView *imageV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"JSNearbyHeaderImageViewID" forIndexPath:indexPath];
        return imageV;
    }
    return nil;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section) {
        return CGSizeMake(SCREEN_WIDTH, kRealValue(30));
    }
    return CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH * 162 / 750);
}
#pragma mark - 性别弹窗
-(void)genderSelect:(UIButton *)sender {
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:self.menuItems];
    menu.menuCornerRadiu = 3;
    menu.showShadow = NO;
    [menu showFromNavigationController:self.navigationController WithX:SCREEN_WIDTH - kRealValue(40)];
}

- (NSMutableArray *)menuItems{
    if (!_menuItems) {
        JS_WeakSelf(self)
        _menuItems = [[NSMutableArray alloc] initWithObjects:
                      
                      [IFMMenuItem itemWithImage:nil
                                           title:[NSString stringWithFormat:@"%@ ", JSLocalizedString(@"All")]
                                          action:^(IFMMenuItem *item) {
                                              weakself.filtrateGender = UserGenderUnKnow;
                                          }],
                      [IFMMenuItem itemWithImage:nil
                                           title:[NSString stringWithFormat:@"%@ ", JSLocalizedString(@"genderMan")]
                                          action:^(IFMMenuItem *item) {
                                              weakself.filtrateGender = UserGenderMale;
                                          }]
                      ,[IFMMenuItem itemWithImage:nil
                                            title:[NSString stringWithFormat:@"%@ ", JSLocalizedString(@"genderWoman")]
                                           action:^(IFMMenuItem *item) {
                                               weakself.filtrateGender = UserGenderFemale;
                                           }]
                      ,nil];
    }
    
    return _menuItems;
}

@end
@implementation JSNearbyHeaderImageView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.imageView = [UIImageView new];
        self.imageView.image = UIImageMake(@"homeHeaderBG");
        [self addSubview:self.imageView];
        
        [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}

@end
@implementation JSNearbyHeaderTitleView
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _titleL = [UILabel new];
        _titleL.text = JSLocalizedString(@"homeSectionTitle");
        JSSetingLableInfo(_titleL, 13, JS_colorWithHex(0x333333));
        [self addSubview:_titleL];
        [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10);
            make.top.and.bottom.equalTo(self);
        }];
    }
    return self;
}
@end

